package com.example.peanutsubway.filter;

import com.example.peanutsubway.dao.MenuInfoDao;
import com.example.peanutsubway.dao.impl.MenuInfoDaoImpl;
import com.example.peanutsubway.entity.MenuInfo;
import com.example.peanutsubway.vo.UserInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 登录验证
 *
 * @Author：liulei
 * @Version：1.0
 * @Date：2021/10/6-14:55
 * @Since:jdk1.8
 * @Description:
 */

public class LoginFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MenuInfoDao menuInfoDao = new MenuInfoDaoImpl();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //  获取session中的登录对象
        HttpSession session = request.getSession();
        UserInfo login = (UserInfo) session.getAttribute("login");

        // 如果用户是完成登录的操作，进入login的servlet时，当前的filter需要对这个请求进行放行
        // 获取用户访问的路径
        String requestURI = request.getRequestURI();// /项目的根目录/访问的url
        if (login == null&&requestURI.contains("/page/login.jsp") || requestURI.equals("/captcha.do") || requestURI.equals("/login.do")||requestURI.contains("/page/main.jsp")||requestURI.contains("page/index.html")||requestURI.contains("/page/404.jsp")){
            filterChain.doFilter(request, response);
        }

        if (login != null) {// 登录成功、访问登录的servlet
            boolean flag = false;
            List<MenuInfo> menuInfos = menuInfoDao.showUserMenuByRoleMinId(login.getRoleid());
            for (MenuInfo menuInfo : menuInfos) {
                if (requestURI.equals(menuInfo.getMenu_url())) {
                    flag = true;
                    break;
                }
            }
            if (flag|| requestURI.equals("/login.do")||requestURI.contains("/page/main.jsp")||requestURI.contains("page/index.html")||requestURI.contains("/page/404.jsp")||requestURI.contains("/page/Personalcenter.jsp")){
                filterChain.doFilter(request, response);
            }
        }
    }

}
